use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
use serde::{Deserialize, Serialize};

#[cfg(test)]
mod tests;


/// 日志配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    /// 日志级别（trace, debug, info, warn, error）
    pub level: String,
    /// 日志格式
    pub format: LogFormat,
    /// 日志输出目标
    pub output: LogOutput,
    /// 文件路径（当输出为文件时）
    pub file_path: Option<String>,
    /// 是否启用控制台输出
    pub console_output: bool,
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: "info".to_string(),
            format: LogFormat::Json,
            output: LogOutput::Console,
            file_path: None,
            console_output: true,
        }
    }
}

/// 日志格式枚举
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LogFormat {
    Json,
    Plain,
}

/// 日志输出目标枚举
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LogOutput {
    Console,
    File,
    Both,
}

pub fn init_logging(config: &LoggingConfig) {
    let level = match config.level.as_str() {
        "trace" => tracing::Level::TRACE,
        "debug" => tracing::Level::DEBUG,
        "info" => tracing::Level::INFO,
        "warn" => tracing::Level::WARN,
        "error" => tracing::Level::ERROR,
        _ => tracing::Level::INFO,
    };

    tracing_subscriber::registry()
        .with(tracing_subscriber::fmt::layer())
        .with(EnvFilter::from_default_env().add_directive(level.into()))
        .init();
}